package ru.spb.osll.myfit.server;

import java.io.PrintStream;
import java.util.HashSet;
import java.util.Map;

import ru.spb.osll.myfit.common.Page;
import ru.spb.osll.myfit.common.PageElement;
import ru.spb.osll.myfit.common.Table;
import ru.spb.osll.myfit.common.TextParsingTools;
import util.GracefulNamer;

public class ImportsPrinter {
	private Map<String, Class<?>> m_fixtures;
	private Configurator m_configurator;

	public ImportsPrinter(Map<String, Class<?>> fixtureClasses, Configurator configurator) {
		m_fixtures = fixtureClasses;
		m_configurator = configurator;
	}

	private String getClassName(Table table) {
		return GracefulNamer.disgrace(table.getData().get(0).get(0)
				.toString()).toLowerCase();
	}

	public void printImports(Page page, PrintStream stream) {
		HashSet<String> importedPackages = new HashSet<String>();

		stream.append(m_configurator.getPathDeclaration());
		
		stream.append(TextParsingTools.TABLE_CELL_SEPARATOR
				+ TextParsingTools.IMPORT_HEADER
				+ TextParsingTools.TABLE_CELL_SEPARATOR
				+ TextParsingTools.CR_and_NEL);

		for (PageElement pageElement : page.getElements())
			if (pageElement instanceof Table) {
				String className = getClassName((Table) pageElement);
				if (m_fixtures.containsKey(className + "fixture")) {
					className = className + "fixture";
				}
				if (m_fixtures.containsKey(className)) {
					String fixturePackage = m_fixtures.get(className)
							.getPackage().getName();
					if (!importedPackages.contains(fixturePackage)) {
						importedPackages.add(fixturePackage);
						stream.append(TextParsingTools.TABLE_CELL_SEPARATOR
								+ fixturePackage
								+ TextParsingTools.TABLE_CELL_SEPARATOR
								+ TextParsingTools.CR_and_NEL);
					}
				}
			}

		stream.append(TextParsingTools.CR_and_NEL);
	}
}
